package cn.jofei.server.http.controller;

import cn.jofei.common.ano.ServerLet;
import cn.jofei.common.thread.CommonEventLoop;
import cn.jofei.common.utils.Utils;
import cn.jofei.server.http.entity.R;
import cn.jofei.server.http.entity.vo.ServerInfo;
import cn.jofei.server.http.entity.vo.SysRegisterInfo;
import cn.jofei.server.interf.ClientConfig;
import cn.jofei.server.interf.ServerQueue;
import io.netty.handler.codec.http.HttpRequest;

import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统内置请求，管理员使用
 *
 * @author Jofei Bao
 * @version ngbao v1.0.2
 * @date 2022/7/10 18:03
 */
@ServerLet(path = "sys")
public class SysController implements ClientConfig {

    /**
     * 当前服务端信息
     *
     * @param params
     * @param request
     * @return
     */
    @ServerLet(path = "info")
    public Object getServerInfo(Map<String, String> params, HttpRequest request) {
        ServerInfo serverInfo = new ServerInfo();
        Map<Integer, List<SysRegisterInfo>> map = ServerQueue.CLIENT_REG_INFO.entrySet().stream().map(e -> new SysRegisterInfo()
                .setMark(e.getKey())
                .setIsTcp(Utils.isNum(e.getKey()) ? 1 : 0)
                .setIp(((InetSocketAddress) e.getValue().channel().remoteAddress()).getHostName())
                .setTime(LocalDateTime.now()))
                .collect(Collectors.groupingBy(SysRegisterInfo::getIsTcp));
        serverInfo.setHttpLists(map.get(0));
        serverInfo.setThreadInfo(CommonEventLoop.info());
        serverInfo.setTcpLists(map.get(1));
        return serverInfo;
    }

    /**
     * 踢出客户端
     *
     * @param params
     * @param request
     * @return
     */
    @ServerLet(path = "removeClient")
    public Object removeClient(Map<String, String> params, HttpRequest request) {
        return R.success();
    }

    /**
     * 移出黑名单
     *
     * @param params
     * @param request
     * @return
     */
    @ServerLet(path = "removeBlackList")
    public Object removeBlackList(Map<String, String> params, HttpRequest request) {
        String ip = params.get("ip");
        return R.success(remove(ip));
    }
}
